<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="每天进步一点点(node.js, javasctipt, vue, vuex, react, redux, mobx, less, sass...)">
    <meta name="keyword" content="">
    <link rel="shortcut icon" href="/img/ironman-draw.png">
    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <title>
        
          微信公众号授权第三方平台 - undefined
        
    </title>

    <link rel="canonical" href="http://yoursite.com/2018/12/22/wechat-OAuth/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS --> 
    <link rel="stylesheet" href="/css/beantech.min.css">
    
    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css">

    <link rel="stylesheet" href="/css/widget.css">

    <link rel="stylesheet" href="/css/rocket.css">

    <link rel="stylesheet" href="/css/signature.css">

    <link rel="stylesheet" href="/css/toc.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">
	<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        
            background-image: url('')
            /*post*/
        
    }
    
</style>

<header class="intro-header">
    <!-- Signature -->
    <div id="signature">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                
                    <div class="post-heading">
                        <div class="tags">
                            
                        </div>
                        <h1>微信公众号授权第三方平台</h1>
                        <h2 class="subheading"></h2>
                        <span class="meta">
                            Posted by eason.L on
                            2018-12-22
                        </span>
                    </div>
                


                </div>
            </div>
        </div>
    </div>
</header>

	
    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">打不死的狒狒</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">Home</a>
                    </li>

                    

                        
                    

                        
                    

                        
                    

                        
                    

                        
                        <li>
                            <a href="/tags/">tags</a>
                        </li>
                        
                    
                    
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    <!-- Modify by Yu-Hsuan Yen -->

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <p>整理下公众号授权，以备不时之需。授权登录并获取用户基本信息。简略步骤如下：<br>  1、用户同意授权 <strong>获取code</strong><br>  2、通过 <strong>code</strong>换取到 <strong>access_token</strong><br>  3、适当时候刷新 <strong>access_token</strong><br>  4、获取用户信息</p>
<h3 id="第一步：用户同意授权，获取code"><a href="#第一步：用户同意授权，获取code" class="headerlink" title="第一步：用户同意授权，获取code"></a>第一步：用户同意授权，获取code</h3><p>  检查用户是否授权登录（如token有效性），打开授权跳转链接：<br>  <em>参考链接(官方示例)，具体链接参数信息参考官网</em><br>  <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">scope为snsapi_base</span><br><span class="line">https:<span class="comment">//open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&amp;redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&amp;response_type=code&amp;scope=snsapi_base&amp;state=123#wechat_redirect</span></span><br><span class="line"></span><br><span class="line">scope为snsapi_userinfo</span><br><span class="line">https:<span class="comment">//open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&amp;redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&amp;response_type=code&amp;scope=snsapi_userinfo&amp;state=STATE#wechat_redirect</span></span><br></pre></td></tr></table></figure></p>
<p>  <strong>注意：微信会对授权链接做正则强匹配校验，如果链接的参数顺序不对，授权页面将无法正常访问，跳转回调redirect_uri，应当使用https链接来确保授权code的安全性。</strong></p>
<h4 id="用户同意授权"><a href="#用户同意授权" class="headerlink" title="用户同意授权"></a>用户同意授权</h4><pre><code>页面跳转至：`redirect_uri/?code=CODE&amp;state=STATE`（*code说明：code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期*）
</code></pre><h3 id="第二步：通过code换取网页授权assess-token"><a href="#第二步：通过code换取网页授权assess-token" class="headerlink" title="第二步：通过code换取网页授权assess_token"></a>第二步：通过code换取网页授权assess_token</h3><p>  如果网页授权的作用域为snsapi_base，则本步骤中获取到网页授权access_token的同时，也获取到了openid，snsapi_base式的网页授权流程即到此为止。<br>  <strong>注意：由于公众号的secret和获取到的access_token安全级别都非常高，必须只保存在服务器，不允许传给客户端。后续刷新access_token、通过access_token获取用户信息等步骤，也必须从服务器发起。</strong></p>
  <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">获取code后，请求以下链接获取access_token：</span><br><span class="line">https:<span class="comment">//api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&amp;secret=SECRET&amp;code=CODE&amp;grant_type=authorization_code</span></span><br></pre></td></tr></table></figure>
<h3 id="第三步：如果需要进行刷新access-token"><a href="#第三步：如果需要进行刷新access-token" class="headerlink" title="第三步：如果需要进行刷新access_token"></a>第三步：如果需要进行刷新access_token</h3><p>  由于access_token拥有较短的有效期，当access_token超时后，可以使用refresh_token进行刷新，refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权。</p>
  <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">获取第二步的refresh_token后，请求以下链接获取access_token：</span><br><span class="line">https:<span class="comment">//api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&amp;grant_type=refresh_token&amp;refresh_token=REFRESH_TOKEN</span></span><br></pre></td></tr></table></figure>
<h3 id="第四步：拉取用户信息-需scope为snsapi-userinfo"><a href="#第四步：拉取用户信息-需scope为snsapi-userinfo" class="headerlink" title="第四步：拉取用户信息(需scope为snsapi_userinfo)"></a>第四步：拉取用户信息(需scope为snsapi_userinfo)</h3><p>  如果网页授权作用域为snsapi_userinfo，则此时开发者可以通过access_token和openid拉取用户信息了。</p>
  <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">http：GET（请使用https协议） https:<span class="comment">//api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&amp;openid=OPENID&amp;lang=zh_CN</span></span><br></pre></td></tr></table></figure>
<h3 id="详细步骤如下："><a href="#详细步骤如下：" class="headerlink" title="详细步骤如下："></a>详细步骤如下：</h3><p>　　1．用户关注微信公众账号。</p>
<p>　　2．微信公众账号提供用户请求授权页面URL。</p>
<p>　　3．用户点击授权页面URL，将向服务器发起请求</p>
<p>　　4．服务器询问用户是否同意授权给微信公众账号(scope为snsapi_base时无此步骤)</p>
<p>　　5．用户同意(scope为snsapi_base时无此步骤)</p>
<p>　　6．服务器将CODE通过回调传给微信公众账号</p>
<p>　　7．微信公众账号获得CODE</p>
<p>　　8．微信公众账号通过CODE向服务器请求Access_Token</p>
<p>　　9．服务器返回Access_Token和OpenID给微信公众账号</p>
<p>　　10．微信公众账号通过Access_Token向服务器请求用户信息(scope为snsapi_base时无此步骤)</p>
<p>　　11．服务器将用户信息回送给微信公众账号(scope为snsapi_base时无此步骤)</p>
<h3 id="项目运用"><a href="#项目运用" class="headerlink" title="项目运用"></a>项目运用</h3><ul>
<li><p>在统一的接口请求返回做拦截，在授权成功的回调地址后拼接token信息</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 获取浏览器信息参数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">BrowserInfo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> u = navigator.userAgent.toLowerCase()</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    isMobile: !!u.match(<span class="regexp">/applewebkit.*mobile.*/</span>), <span class="comment">// 是否为移动终端</span></span><br><span class="line">    isIos: !!u.match(<span class="regexp">/\(i[^;]+;( u;)? cpu.+mac os x/</span>), <span class="comment">// ios终端</span></span><br><span class="line">    isAndroid: u.indexOf(<span class="string">'android'</span>) &gt; <span class="number">-1</span> || u.indexOf(<span class="string">'adr'</span>) &gt; <span class="number">-1</span>, <span class="comment">// android终端</span></span><br><span class="line">    isWx: u.indexOf(<span class="string">'micromessenger'</span>) &gt; <span class="number">-1</span>, <span class="comment">// 是否微信</span></span><br><span class="line">    isApp: u.indexOf(<span class="string">'***app'</span>) &gt; <span class="number">-1</span>, <span class="comment">// 是否 app</span></span><br><span class="line">    isSimpleBrowser: u.indexOf(<span class="string">'micromessenger'</span>) === <span class="number">-1</span> &amp;&amp; u.indexOf(<span class="string">'***app'</span>) === <span class="number">-1</span>, <span class="comment">// 普通浏览器环境</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">axios.interceptors.response.use(<span class="function"><span class="params">response</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (response.data.code === <span class="number">-1</span>) &#123;</span><br><span class="line">    <span class="comment">// 这里可以区分不同的端，如微信环境、普通浏览器、嵌入app等，做不同的操作</span></span><br><span class="line">    <span class="keyword">if</span> (BrowserInfo.isWx) &#123;</span><br><span class="line">      <span class="built_in">window</span>.location.href = <span class="string">`<span class="subst">$&#123;baseURL&#125;</span>/api/userWx/loginAuth?redirectUri=<span class="subst">$&#123;<span class="built_in">encodeURIComponent</span>(WxAuthHashUrl.to(currentRoute.fullPath))&#125;</span>&amp;platformType=<span class="subst">$&#123;platformType&#125;</span>`</span></span><br><span class="line">      <span class="keyword">return</span> <span class="built_in">Promise</span>.reject(err)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>在<code>vue</code>的<code>router</code>钩子函数处理<code>token</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">router.beforeEach(to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">  <span class="keyword">if</span> (to.query.token) &#123;</span><br><span class="line">    session.setAttribute(<span class="string">'token'</span>, to.query.token)</span><br><span class="line">    <span class="keyword">let</span> href = to.fullPath</span><br><span class="line">    href = href.replace(<span class="string">'token='</span>, <span class="string">'baseParam=818'</span>)</span><br><span class="line">    next(href)</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    next()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>在统一的接口请求做token传参处理</p>
<pre><code class="javascript">
  axios.interceptors.request.use(<span class="function">(<span class="params">config</span>) =&gt;</span> {
    <span class="keyword">let</span> token = localStorage.getItem(<span class="string">'sessionToken'</span>)
    config.headers.common[<span class="string">'TOKEN'</span>] = token
    config.cache = <span class="literal">false</span>
    thisHttp.url = config.url
    <span class="comment">// 公共参数</span>
    <span class="keyword">const</span> commonParams = {
      _t: <span class="keyword">new</span> <span class="built_in">Date</span>().getTime(),
      ...
    }
    config.params = config.params || {}
    <span class="built_in">Object</span>.assign(config.params, commonParams)
    <span class="keyword">return</span> config
  }, (err) =&gt;
    <span class="built_in">Promise</span>.reject(err)
  )
}

</code></pre>
</li>
</ul>

                

                <hr>
                <!-- Pager -->
                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/2018/12/22/wechat-miniapp/" data-toggle="tooltip" data-placement="top" title="小程序登录授权">&larr; Previous Post</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/2018/12/22/react-proxy/" data-toggle="tooltip" data-placement="top" title="react多个代理时的设置方法">Next Post &rarr;</a>
                        </li>
                    
                </ul>

                <br>
                
                <!-- require APlayer -->
                

                <!-- duoshuo Share start -->
                
                <!-- 多说 Share end-->

                <!-- 多说评论框 start -->
                
                <!-- 多说评论框 end -->

                <!-- disqus comment start -->
                
                <!-- disqus comment end -->

                

            </div>
            
            <!-- Tabe of Content -->
            <!-- Table of Contents -->

                
            <!-- Sidebar Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
                <hr>
                <h5>FRIENDS</h5>
                <ul class="list-inline">

                    
                        <li><a href="http://blog.csdn.net/123" target="_blank">CSDN 东方</a></li>
                    
                        <li><a href="http://dockone.io/people/123" target="_blank">掘金 东方</a></li>
                    
                        <li><a href="https://yq.aliyun.com/u/123" target="_blank">博客园 东方</a></li>
                    
                </ul>
                
            </div>
        </div>
    </div>
</article>










    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                

                

                

                

                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; eason.L 2018 
                    <br>
                    Theme by <a href="http://beantech.org">BeanTech</a> 
                    <span style="display: inline-block; margin: 0 5px;">
                        <i class="fa fa-heart"></i>
                    </span> 
                    re-Ported by <a href="https://github.com/eason1999">eason.L</a> | 
                    <iframe style="margin-left: 2px; margin-bottom:-5px;" frameborder="0" scrolling="0" width="91px" height="20px" src="https://ghbtns.com/github-btn.html?user=eason1999&repo=hexo-theme-huweihuang&type=star&count=true">
                    </iframe>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://yoursite.com/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->




<!-- Baidu Tongji -->






	<a id="rocket" href="#top" class=""></a>
	<script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
    <script type="text/javascript" src="/js/toc.js?v=1.0.0" async=""></script>
<!-- Image to hack wechat -->
<img src="http://yoursite.com/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

</body>

</html>
